package com.googlecode.lazyrecords.sql.expressions;


public class JoinQualifier extends AbstractQualifier {
    private final Qualifier left;
    private final Qualifier right;

    public JoinQualifier(final String left, final String right) {
        this.left = Qualifier.qualifier(left);
        this.right = Qualifier.qualifier(right);
    }

    private QualifiedJoin qualifyQualifiedJoin(final QualifiedJoin qualifiedJoin) {
        return AnsiQualifiedJoin.qualifiedJoin(left.qualify(qualifiedJoin.left()), qualifiedJoin.joinType(),
                right.qualify(qualifiedJoin.right()), qualify(qualifiedJoin.joinSpecification()));
    }

    private JoinCondition qualifyJoinCondition(JoinCondition joinCondition){
        return JoinCondition.joinCondition(left.qualify(joinCondition.left()), right.qualify(joinCondition.right()));
    }

    @Override
    public <T extends Expression> T qualify(T expression) {
        if(expression instanceof QualifiedJoin) {
            return (T)qualifyQualifiedJoin((QualifiedJoin) expression);
        }
        if(expression instanceof JoinCondition) {
            return (T)qualifyJoinCondition((JoinCondition) expression);
        }
        return expression;
    }
}
